package com.xuliugen.image.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpException;

import com.xuliugen.image.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

/**
 * 管理Image的Manager
 */
public class ImageManager {

	//将Bitmap存放在一个软引用的Map中
	Map<String, SoftReference<Bitmap>> imgCache; 

	private Context context;

	//public static Bitmap defualtImage; //默认的图像

	public ImageManager(Context context) {
		this.context = context;
		imgCache = new HashMap<String, SoftReference<Bitmap>>();

		// 将drawable转化为Bitmap
		//defualtImage = drawabltToBitmap(context.getResources().getDrawable(R.drawable.usericon));
		// defualtImage =
		// ((BitmapDrawable)context.getResources().getDrawable(R.drawable.usericon)).getBitmap();
	}

	/**
	 * 判断imgCache是否存在
	 */
	public boolean contains(String url) {
		return imgCache.containsKey(url);
	}

	/**
	 * 从本地获取图片信息:MapCache和File
	 */
	public Bitmap getFromLocal(String url) {
		Bitmap bitmap = null;

		bitmap = this.getFromMapCache(url); //首先从MapCache中获取

		if (null == bitmap) {
			bitmap = getFromFile(url); //然后从File中获取
		}
		return bitmap;
	}

	/**
	 * 从文件中获取Bitmap
	 */
	public Bitmap getFromFile(String url) {

		String fileName = this.getMd5(url);

		FileInputStream is = null;

		try {
			is = context.openFileInput(fileName); //打开一个文件流

			return BitmapFactory.decodeStream(is);
		} catch (FileNotFoundException e) {
			return null;
		} finally {
			if (null != is) {
				try {
					is.close();
				} catch (Exception ex) {}
			}
		}
	}

	/**
	 * 从Map缓存中获取BitMap
	 */
	public Bitmap getFromMapCache(String url) {
		Bitmap bitmap = null;

		SoftReference<Bitmap> ref = null;

		synchronized (this) {
			ref = imgCache.get(url);
		}
		if (null != ref) {
			bitmap = ref.get();
		}
		return bitmap;
	}

	/**
	 * 执行下载的时候
	 */
	public Bitmap safeGet(String url) throws HttpException {

		Bitmap bitmap = this.getFromFile(url);

		if (null != bitmap) { //如果从file中获得到加入到cache中
			synchronized (this) {  
				imgCache.put(url, new SoftReference<Bitmap>(bitmap)); //将下载之后的文件保存在map中
			}
			return bitmap;
		}

		return downloadImg(url);

	}

	/**
	 * 下载图片并保持文件到系统缓存
	 */
	public Bitmap downloadImg(String urlStr) throws HttpException {

		try {
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			String fileName = writerToFile(getMd5(urlStr),connection.getInputStream());

			return BitmapFactory.decodeFile(fileName);

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 将图片文件写到file中
	 */
	public String writerToFile(String fileName, InputStream is) {

		BufferedInputStream bis = null;

		BufferedOutputStream bos = null;

		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(context.openFileOutput(fileName,Context.MODE_PRIVATE));

			byte[] buffer = new byte[1024];
			int length;

			while ((length = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, length);
			}

		} catch (Exception e) {

		} finally {

			try {
				if (null != bis) {
					bis.close();
				}
				if (null != bos) {
					bos.flush();
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return context.getFilesDir() + "/" + fileName;
	}

	private String getMd5(String src) {
		return MD5Util.getMD5String(src);
	}

	/**
	 * 将drawable转化为Bitmap
	 */
	private Bitmap drawabltToBitmap(Drawable drawable) {

		BitmapDrawable tempDrawable = (BitmapDrawable) drawable;
		return tempDrawable.getBitmap();
	}
}
